package com.etoak.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.service.RedisService;
import com.etoak.vo.CodeVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    DefaultKaptcha kaptcha;
    @Autowired
    RedisService redisService;
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/getCode")
    public ResultVO<CodeVO> getCode() throws IOException {
        String text=defaultKaptcha.createText();
        String[] split = text.split(StrUtil.AT);
        String uuid = IdUtil.simpleUUID();
        String redisKey= CommonConstant.KAPTCHA_PREFIX+uuid;
        redisService.setex(redisKey,split[1],5, TimeUnit.MINUTES);
        BufferedImage bufferedImage = defaultKaptcha.createImage(split[0]);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", outputStream);
        String base64 = Base64.encode(outputStream.toByteArray());
        CodeVO codeVO = new CodeVO("data:image/png;base64," + base64,uuid);
        return ResultVO.success(codeVO);
    }
}
